//
//  CBDSampleDetailsViewController.m
//  BESTWallpaper
//
//  Created by MAC on 2019/7/24.
//  Copyright © 2019 CarMayor. All rights reserved.
//

#import "CBDSampleDetailsViewController.h"
#import "CBDSampleDetailsCell.h"
#import "CBDNetManager.h"
#import "CBDRecommendModel.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#import <YYKit.h>
#import <Masonry.h>
#import "SampleDetailsHeaderView.h"
#import <SDWebImageDownloader.h>
#import <SVProgressHUD.h>
@interface CBDSampleDetailsViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)NSMutableArray <CBDRecommendModel *> *dataSource;
@property(nonatomic,strong)SampleDetailsHeaderView *header;
@property(nonatomic,assign)NSInteger    currentIndex;
@end

@implementation CBDSampleDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view
    self.fd_prefersNavigationBarHidden = true;
   
    [self setupUI];
    [self loadData];
}

- (BOOL)prefersStatusBarHidden {
    return true;
}

- (void)loadData {
    NSString *urlString = [NSString stringWithFormat:@"http://api.breadtrip.com/trips/%@/trackpoints/",self.sampleId];
    [CBDNetManager requestWithUrl:urlString requestType:HttpRequestTypeGet parameter:nil completation:^(id object) {
        NSArray *trackpoints = object[@"trackpoints"];
        self.dataSource = [NSMutableArray array];
        [trackpoints enumerateObjectsUsingBlock:^(NSArray *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            CBDRecommendModel *model = [CBDRecommendModel new];
            
            model.desc = obj[5];
            model.cover_image_default = obj[6];
            NSDate *date = [NSDate dateWithTimeIntervalSince1970:[obj[7] floatValue]];
            
            model.first_day = [date stringWithFormat:@"yyyy.MM.dd"];
            [self.dataSource addObject:model];
        }];
        [self.collectionView reloadData];
        
    } failure:^(NSError *error) {
//        self.progressLine.hidden = YES;
        
//        if (self.datas.count == 0) {
//            self.failPic.hidden = NO;
//        }else {
//            self.failPic.hidden = YES;
//        }
        
    }];
    
//    [2371855187, 135.7741, 34.99318, 135.7741, 34.99318, "", "http://photos.breadtrip.com/photo_2019_06_08_57d2852bc5c1012e64ab5a0d30559e0e.jpg?imageView/2/w/960/q/85", 1559903940.0, -1],
    
}

- (void)setupUI {
    
    
    self.header = [SampleDetailsHeaderView nibInitializtion];
    self.header.frame = CGRectMake(0, 0, kScreenWidth, self.statutBarHeih + 44);
    [self.view addSubview:self.header];
    
    __weak typeof(self) ws = self;
    self.header.back = ^{
        
        [ws.navigationController popViewControllerAnimated:true];
    };
    
    self.header.save = ^{
        NSURL *url = [NSURL URLWithString:ws.dataSource[ws.currentIndex].cover_image_default];
        [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:url completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
            UIImageWriteToSavedPhotosAlbum(image, ws, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)ws);
        }];
    };
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
   
    self.collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
    self.collectionView.pagingEnabled = true;
    [self.collectionView registerNib:[UINib nibWithNibName:@"CBDSampleDetailsCell" bundle:nil] forCellWithReuseIdentifier:@"CBDSampleDetailsCell"];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsHorizontalScrollIndicator = true;
    self.collectionView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
    [self.view insertSubview:self.collectionView atIndex:0];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
   
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error == nil) {
        [SVProgressHUD showSuccessWithStatus:@"保存成功"];
    } else {
        [SVProgressHUD showErrorWithStatus:@"保存失败"];
    }
}

- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    CBDSampleDetailsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CBDSampleDetailsCell" forIndexPath:indexPath];
    [cell.img setImageURL:[NSURL URLWithString:self.dataSource[indexPath.row].cover_image_default]];
    cell.desc.text = self.dataSource[indexPath.row].desc;
    cell.info.text = [NSString stringWithFormat:@"摄影师：%@    时间：%@",self.author,self.dataSource[indexPath.row].first_day];
    
    cell.bottomView.hidden = self.header.isHidden;
    cell.bottomView.alpha = self.header.alpha;
    cell.tapedCall = ^{
        if (self.header.isHidden) {
            self.header.hidden = false;
            [UIView animateWithDuration:0.2 animations:^{
                self.header.alpha = 1;
            }];
        }else {
            [UIView animateWithDuration:0.2 animations:^{
                self.header.alpha = 0;
            } completion:^(BOOL finished) {
                self.header.hidden = true;
            }];
        }
    };
    return  cell;
}

- (NSInteger)collectionView:(nonnull UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(kScreenWidth, kScreenHeight);
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    self.currentIndex = scrollView.contentOffset.x / kScreenWidth;
}

@end
